<template>
  <el-form ref="phoneFormRef" :model="phoneForm" :rules="phoneFormRules" :label-width="100" size="large">
    <!-- 解决自动填充的问题 start -->
    <!-- <input type="password" autocomplete="current-password" name="password" style="display: none; opacity: 1" /> -->
    <el-input style="display: none" name="username"></el-input>
    <!-- 解决自动填充的问题 end -->
    <el-form-item prop="mobile" label="手机号码" required>
      <el-input v-model="phoneForm.mobile" placeholder="请输入手机号码" :maxlength="11" clearable>
        <template #prefix>
          <el-icon class="el-input__icon">
            <Iphone />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="validCode" label="验证码">
      <el-row type="flex" justify="space-around" style="width: 100%">
        <el-input
          v-model.number="phoneForm.validCode"
          oninput="if(value.length>6)value=value.slice(0,6)"
          :disabled="phoneForm.mobile.length < 11"
          placeholder="请输入验证码"
          autocomplete="off"
          :maxlength="6"
        >
          <template #suffix>
            <el-button @click="sendVerifyCode" text type="primary" :disabled="state.txtVerifyCode != '获取验证码'">{{
              state.txtVerifyCode
            }}</el-button>
          </template>
        </el-input>
      </el-row>
    </el-form-item>
    <template v-if="props.type == 'password'">
      <el-form-item label="新密码" prop="newPassword" required>
        <el-input v-model.trim="phoneForm.newPassword" show-password> </el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword" required>
        <el-input v-model.trim="phoneForm.confirmPassword" show-password> </el-input>
      </el-form-item>
    </template>
  </el-form>
  <Verify
    mode="pop"
    :captcha-type="'blockPuzzle'"
    :img-size="{ width: '400px', height: '200px' }"
    ref="verifyRef"
    @success="handleSuccess"
  ></Verify>
</template>

<script lang="ts" setup>
import { ElMessage, FormInstance } from "element-plus";
import { onMounted, reactive, ref, toRefs } from "vue";
import { checkPhoneNumber } from "@/utils/eleValidate";
import { Login } from "@/api/interface";
import { PLATFORM } from "@/config";
import Verify from "@/components/verifition/Verify.vue";
export interface PhoneCodeProps {
  sendCodeApi?: (params: any) => Promise<any>;
  sendCodeScene?: number;
  submitApi?: (params: any) => Promise<any>;
  type?: string;
  platform?: string;
}
export interface IPhoneCodeFrom {
  /** 手机号 */
  mobile: string;
  //验证码
  validCode: string;
  // 新密码
  newPassword: string;
  // 确认密码
  confirmPassword: string;
  // 人机码
  captchaVerification: string;
}

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入新密码"));
  } else {
    if (phoneForm.confirmPassword !== "") {
      if (!phoneFormRef.value) return;
      phoneFormRef.value.validateField("confirmPassword", () => null);
    }
    callback();
  }
};
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入确认密码"));
  } else if (value !== phoneForm.newPassword) {
    callback(new Error("两次输入不一致!"));
  } else {
    callback();
  }
};
const props = withDefaults(defineProps<PhoneCodeProps>(), {
  platform: PLATFORM,
});
const phoneFormRef = ref<FormInstance>();
const phoneFormRules = {
  mobile: [
    { required: true, message: "请输入手机号" },
    {
      validator: checkPhoneNumber,
    },
  ],
  validCode: [{ required: true, message: "请输入验证码", trigger: "blur" }],
  newPassword: [
    { validator: validatePass, trigger: "blur" },
    { required: true, trigger: "blur", message: "请输入新密码" },
  ],
  confirmPassword: [
    { validator: validatePass2, trigger: "blur" },
    { required: true, trigger: "blur", message: "请输入确认密码" },
  ],
};
const verifyRef = ref<InstanceType<typeof Verify>>();
const handleSuccess = param => {
  phoneForm.captchaVerification = param.captchaVerification || "";
  sendVerifyCode();
};
const phoneForm = reactive<Login.PhoneChangePwd>({
  mobile: "",
  validCode: "",
  newPassword: "",
  confirmPassword: "",
  captchaVerification: "",
});
const state = reactive({
  codeLoginDisabled: true,
  second: 60,
  txtVerifyCode: "获取验证码",
  codeData: {
    text: "获取验证码",
    disabled: false,
  },
});
const countdown = () => {
  if (state.second == 0) {
    state.txtVerifyCode = "获取验证码";
    state.second = 60;
  } else {
    state.txtVerifyCode = `${state.second}s 重新获取`;
    state.second--;
    setTimeout(() => {
      countdown();
    }, 1000);
  }
};
const sendVerifyCode = () => {
  phoneFormRef.value?.validateField(["mobile"], valid => {
    if (!valid) return;
    const data = {
      mobile: phoneForm.mobile,
      platform_type: props.platform,
      scene: props.sendCodeScene,
      captchaVerification: phoneForm.captchaVerification,
    };
    props
      .sendCodeApi(data)
      .then(() => {
        state.codeLoginDisabled = false;
        countdown();
      })
      .catch(err => {
        if (err.code == 602) {
          verifyRef.value.show();
        }
      })
      .finally(() => (phoneForm.captchaVerification = ""));
  });
};
const submit = () => {
  return new Promise((resolve, reject) => {
    phoneFormRef.value?.validate(valid => {
      if (!valid) return;
      if (props.type == "password") {
        const params = {
          mobilePhone: phoneForm.mobile,
          newPwd: phoneForm.newPassword,
          verificationCode: phoneForm.validCode,
        };

        props.submitApi!(params).then(res => {
          if (res.code == 200) {
            ElMessage.success("密码修改成功");
            resolve(true);
          }
        });
      } else {
        resolve(JSON.parse(JSON.stringify(phoneForm)));
      }
    });
  });
};
defineExpose({
  submit,
  phoneFormRef,
});
</script>
<style lang="scss" scoped></style>
